package ch.supsi.parentalcontrol;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import ch.supsi.mobile.core.Address;
import ch.supsi.mobile.core.Page;

public class GestioneSchedaAdmin implements ActionListener{

	private JList whiteList = new JList();
	private JList blackList = new JList();
	
	private AdminPanel ap;
	
	public GestioneSchedaAdmin(AdminPanel ap){
		this.ap = ap;
	}
	
	@Override
	public void actionPerformed(ActionEvent evt) {
		JButton source = (JButton)evt.getSource();
		if(source.getText().equals(">>")){
			AddInBlack(this.ap);
		}else if(source.getText().equals("<<")){
			AddInWhite(this.ap);
		}else{
			AddNewObject(this.ap);
		}
	}
	
	private void AddInBlack(AdminPanel ap){
		try{
			ap.addBlackObject(ap.getWhiteList().getSelectedIndex());
		}catch(Exception e){
			JOptionPane.showMessageDialog(null,"Devi selezionare un'elemento da spostare","Error",JOptionPane.WARNING_MESSAGE);
		}
	}
	
	private void AddInWhite(AdminPanel ap){
		try{
			ap.addWhiteObject(ap.getBlackList().getSelectedIndex());
		}catch(Exception e){
			JOptionPane.showMessageDialog(null,"Devi selezionare un'elemento da spostare","Error",JOptionPane.WARNING_MESSAGE);
		}
	}
	
	private void appendElement(JList list, Object el){
		DefaultListModel model = (DefaultListModel) list.getModel();
		model.addElement(el);
		list.setModel(model);
	}

	private void AddNewObject(AdminPanel ap){
		
		String type = ap.getType();
		
		if(type.equalsIgnoreCase("Address")){
			JTextField name = new JTextField();
			JTextField number = new JTextField();
			JTextField id = new JTextField();
		
			Object complexAddress[] = {"Name", name, "Number", number, "Id", id};
			
			if(JOptionPane.showConfirmDialog(null, complexAddress, "newAddress" , JOptionPane.OK_CANCEL_OPTION) == JOptionPane.YES_OPTION){
				Address newAddress = new Address(id.getText(), name.getText(), number.getText());
				ap.getWhiteListModel().addElement(newAddress);	
			}
		}
		
		if(type.equalsIgnoreCase("Browser")){
			JTextField content = new JTextField();
			JTextField url = new JTextField();
						
			Object complexBrowser[] = {"Content", content, "URL", url};
			
			if(JOptionPane.showConfirmDialog(null, complexBrowser, "newBrowser" , JOptionPane.OK_CANCEL_OPTION) == JOptionPane.YES_OPTION){
				Page newBrowser = new Page(url.getText(), content.getText());
				ap.getWhiteListModel().addElement(newBrowser);	
			}
		}
		
	}
	
	private void addElement(JList list, Object el){
		DefaultListModel model = new DefaultListModel();
		model.addElement(el);
		list.setModel(model);
	}
		
}
